<?php
namespace app\admin\controller;

use app\admin\model\Tag as tagModel;
use tool\Log;

class Tag extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $limit = input('param.limit');
            $keywords = input('param.keywords');
            $where = [];
            if (!empty($keywords)) {
                $where[] = ['tagname', 'like', '%' . $keywords . '%'];
            }

            $tag = new tagModel();
            $list = $tag->getTagname($limit, $where);
            if (0 == $list['code']) {
                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }
            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }
        return $this->fetch();
    }
    // 添加tag
    public function add()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $tag = new tagModel();
            $res = $tag->addTag($param);

            Log::write("添加Tag：" . $param['tagname']);

            return json($res);
        }

        return $this->fetch();
    }
    // 编辑tag
    public function edit()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $tag = new tagModel();
            $res = $tag->editTag($param);

            Log::write("编辑tag：" . $param['tagname']);

            return json($res);
        }

        $id = input('param.id');
        $tag = new tagModel();

        $this->assign([
            'item' => $tag->getTagById($id)['data'],
        ]);

        return $this->fetch('edit');
    }

    /**
     * 删除tag
     * @return \think\response\Json
     */
    public function del() {
        if (request()->isAjax()) {
            $id = input('param.id');

            $tag = new tagModel();
            $res = $tag->delTag($id);

            Log::write("删除tag：" . $id);
            return json($res);
        }
    }

    // 修改tagname
    public function editTagname() {
        if (request()->isAjax()) {
            $param['id'] = input('param.id');
            $param['tagname'] = input('param.tagname');
            $param['update_time'] = date('Y-m-d H:i:s');
            $tag = new tagModel();
            if (false !== $tag->save($param, ['id' => $param['id']])) {
                return reMsg(0, '', '修改tag成功');
            } else {
                return reMsg(-1, '', '修改tag失败');
            }
        }
    }

    // 批量删除操作
    public function isDelAll() {
        if (request()->isAjax()) {
            $tag_id = input('param.id');

            $tagModel = new tagModel();
            if($tagModel->where('id', 'in', $tag_id)->delete()) {
                return reMsg('0','','删除成功');
            } else {
                return reMsg('-1','','删除失败');
            }
        }
    }

}